package com.dongbo.recorder.screenrecord.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.bean.WxPayModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PayUtil {

    static Activity mActivity;

    public PayUtil(Builder builder) {
        mActivity = builder.activity;
    }

    public static class Builder {
        private Activity activity;
        private static final int WXPAY = 1;//微信
        private static final int ALIPAY = 2;//支付宝

        public Builder(Activity activity) {
            this.activity = activity;
        }

        static IAlipayListener mListener;

        public void setListener(IAlipayListener listener) {
            mListener = listener;
        }

        public interface IAlipayListener {
            void paySuccess();

            void startRequest();//开始请求服务器

            void endRequest();//请求结束

            void requestError();//请求服务器错误
        }

        public void wxPay(String goodsId) {
            if (null != mListener) {
                mListener.startRequest();
            }
//            String json = new Gson().toJson(new PayJson(AppImpl.getInstance().getDeviceNo(),
//                    money, 6, "Android"));
//            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
            RequestBody body = new FormBody.Builder()
                    .add("appId", Constants.APP_ID)
                    .add("mealId", goodsId)
                    .add("payWay", "1")
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(Constants.BASE_URL + "/app/order/createOrder")
                    .addHeader("Authorization", AppLpds.getInstance().getToken())
                    .post(body)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (null != mListener) {
                        mListener.requestError();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
//                    if (!TextUtils.isEmpty(data)) {
//                        byte[] bytes = Base64.decode(data);
//                        if (null != bytes && bytes.length > 0) {
//                            json = new String(Base64.decode(data));
                    Log.i("weixinfanhu", "json==" + json);
                    if (TextUtils.isEmpty(json)) {
                        if (null != mListener) {
                            mListener.requestError();
                        }
                        return;
                    }
                    NetResponse<WxPayModel> info = new Gson().fromJson(json, new TypeToken<NetResponse<WxPayModel>>() {
                    }.getType());
                    if (info.getStatusCode() == 200) {
//                                Log.i("VIP", "json==" + json);
                        startWxPay(info.getData());
                        if (null != mListener) {
                            mListener.endRequest();
                        }
                    } else {
                        if (null != mListener) {
                            mListener.requestError();
                        }
                    }
//                        } else {
//                            if (null != mListener) {
//                                mListener.requestError();
//                            }
//                        }
//                    } else {
//                        if (null != mListener) {
//                            mListener.requestError();
//                        }
//                    }
                }
            });
        }

        private void startWxPay(WxPayModel model) {
            IWXAPI api = WXAPIFactory.createWXAPI(activity, Constants.WX_APP_ID);
            api.registerApp(Constants.WX_APP_ID);
            PayReq req = new PayReq();
            req.appId = model.getAppId();
            req.partnerId = model.getPartnerId();
            req.prepayId = model.getPrepayId();
            req.nonceStr = model.getNonceStr();
            req.timeStamp = model.getTimestamp();
            req.packageValue = model.getPackageValue();
            req.sign = model.getSign();
//            Log.i("VIP", "checkArgs=" + req.checkArgs());//这个只有在true的情况才有可能调起支付页面。
            api.sendReq(req);
        }

        public void aliPay(String goodsId) {
            if (null != mListener) {
                mListener.startRequest();
            }
            String token = Constants.SIGN_KEY + "app/mall/alipayGeneratOrder";
            String sign = MD5.getMessageDigest(token);
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("sign", sign)
                    .add("appexpId", Constants.WX_APP_ID)
                    .add("uid", AppLpds.getInstance().getUserId())
                    .add("goodsId", goodsId)
                    .add("orderType", "0")
                    .build();
            Request request = new Request.Builder()
                    .url(Constants.BASE_URL + "app/mall/alipayGeneratOrder")
                    .post(body)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
//                    runOnUiThread(() -> {
//                        Tt.show(VipActivity.this, e.getMessage());
//                    });
                    if (null != mListener) {
                        mListener.requestError();
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    if (TextUtils.isEmpty(body)) {
                        return;
                    }
                    String json = new String(Base64.decode(body));
                    if (TextUtils.isEmpty(json)) {
                        return;
                    }
//                    Log.i("支付宝", json);
                    NetResponse<String> info = null;
                    try {
                        info = new Gson().fromJson(json, new TypeToken<NetResponse<String>>() {
                        }.getType());
                        if (info != null
                                && info.isSuccess()
                                && info.getStatusCode() == 1) {
                            if (info.getData() != null) {
                                if (null != mListener) {
                                    mListener.endRequest();
                                }
                                startAliPay(info.getData());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (null != mListener) {
                            mListener.requestError();
                        }
                    }
                }
            });
//            String json = GsonUtils.fromObject(new AliPayJson(MyApplication.getInstance().getLoginData().getUserinfoId(), money, "Android"));
//            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
//            HttpMgr.getApi().aliPay(body).enqueue(new CommonCallback<StringResp>() {
//                @Override
//                public void onResponse(Call<StringResp> call, Response<StringResp> response) {
//                    super.onResponse(call, response);
//                    if (null != mListener) {
//                        mListener.endRequest();
//                    }
//                    StringResp resp = response.body();
//                    if (null != resp && resp.isSuccess()) {
//                        String info = resp.getData();
//                        startAliPay(info);
//                    }
//                }
//
//                @Override
//                public void onFailure(Call<StringResp> call, Throwable t) {
//                    super.onFailure(call, t);
//                    if (null != mListener) {
//                        mListener.requestError();
//                    }
//                }
//            });
        }

        private static final int SDK_PAY_FLAG = 101;
        private static Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        Map<String, String> result = (Map<String, String>) msg.obj;
                        String resultStatus = result.get("resultStatus");
                        if ("9000".equals(resultStatus)) {
                            //                        String response = result.get("result");
//                            Ll.i("PAY", result.toString());
//                            ToastUtils.show("支付成功");
                            Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
                            if (null != mListener) {
                                mListener.paySuccess();
                            }
                        }
                        break;
                    }
                    default:
                }
            }
        };

        private void startAliPay(final String info) {
            Runnable payRunnable = () -> {
                Log.i("info", info);
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(info, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }

    }


}
